<template>
  <div>
    <el-dialog
      v-model="createVisible"
      :title="operation == 'create' ? '添加菜单' : '编辑菜单'"
      @before-ok="createOk"
      @close="close(createRef)"
      width="800px"
      top="100px"
    >
      <el-form
        :model="createForm"
        ref="createRef"
        :rules="createRules"
        label-width="120px"
        size="default"
        v-loading="createLoading"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="菜单名称：" prop="menu_name">
              <el-input
                v-model="createForm.menu_name"
                placeholder="请输入菜单名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类型：" prop="type">
              <el-radio-group v-model="createForm.type">
                <el-radio :label="1" border>菜单</el-radio>
                <el-radio :label="2" border>应用</el-radio>
                <el-radio :label="3" border>事件</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父级分类：" prop="pid">
              <el-cascader
                v-model="createForm.pid"
                :options="menusCascader"
                @change="pidChange"
                filterable
                clearable
                class="form-select-fil"
                :props="{
                  emitPath: false,
                  checkStrictly: true,
                  disabled: 'selected',
                }"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="'图标：'" prop="icon">
              <el-input
                v-model="createForm.icon"
                :prefix-icon="
                  () => {
                    return h('span', { class: ['icon', createForm.icon] });
                  }
                "
              >
                <template #append>
                  <el-button
                    @click="
                      () => {
                        selectModalIconRef.open();
                      }
                    "
                  >
                    图标
                  </el-button>
                  <select-icon-modal
                    ref="selectModalIconRef"
                    @change="iconChange"
                  ></select-icon-modal>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" v-if="createForm.type != 3">
            <el-form-item label="路由地址：" prop="menu_path">
              <el-input
                v-model="createForm.menu_path"
                placeholder="请输入路由地址"
              >
              </el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="接口标识：" prop="api_rule">
              <el-input
                v-model="createForm.api_rule"
                placeholder="请输入接口标识"
              >
                <template #append>
                  <el-button
                    icon="Menu"
                    @click="
                      () => {
                        selectRuleRef.open();
                      }
                    "
                  />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识：" prop="menu_node">
              <el-input
                v-model="createForm.menu_node"
                placeholder="请输入权限标识"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="参数：" prop="params">
              <el-input v-model="createForm.params"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序：" prop="sort">
              <el-input-number
                v-model="createForm.sort"
                :min="0"
                :max="10000"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态：" prop="status">
              <el-radio-group v-model="createForm.status">
                <el-radio
                  v-for="item in StatusEnum"
                  :label="item.value"
                  :key="item.value"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="flex center">
          <el-button @click="createVisible = false">取消</el-button>
          <el-button type="primary" @click="createOk(createRef)" :loading="btnLoading" :disabled="btnLoading"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <select-rule-modal
      ref="selectRuleRef"
      @change="ruleChange"
    ></select-rule-modal>
  </div>
</template>
<script lang="ts" >
export default {
  name: "menusCreateComponent",
};
</script>
  <script lang="ts" setup>
import { ref, h, watch, reactive, getCurrentInstance, nextTick } from "vue";
import type { CommonProps, FormInstance, FormRules } from "element-plus";
import { useConfig } from "@/store";
import { getCascader, create, getDetail, update } from "@/api/system/menus";
import type { Result , ResultError } from "@/types"
const {
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const configStore = useConfig();

const StatusEnum = ref(configStore.getEnumItem("StatusEnum"));

const operation = ref("create");

const operationId = ref(0);

const createVisible = ref(false);

const createRef: any = ref<typeof FormInstance>();

const createForm = ref({
  type: 1,
  menu_name: "",
  pid: null,
  menu_path: "",
  menu_node: "",
  params: "",
  icon: "",
  sort: 0,
  status: 1,
  api_rule:''
});

const toInit = () => {
  initCascader();
  if (!operationId.value) {
    return;
  }
  createLoading.value = true;
  getDetail({ id: operationId.value })
    .then((res:Result) => {
      createForm.value.type = res.data.type;
      createForm.value.menu_name = res.data.menu_name;
      createForm.value.pid = res.data.pid;
      createForm.value.menu_path = res.data.menu_path;
      createForm.value.menu_node = res.data.menu_node;
      createForm.value.params = res.data.params;
      createForm.value.icon = res.data.icon;
      createForm.value.sort = res.data.sort;
      createForm.value.status = res.data.status.value;
      createForm.value.api_rule = res.data.api_rule;
      
      createLoading.value = false;
    })
    .catch((err:ResultError) => {
      $utils.errorMsg(err);
    });
};

const createRules: any = reactive({
  menu_name: [{ required: true, message: "菜单名称不能为空！" }],
});

const createLoading: any = ref(false);

const emit = defineEmits(["success"]);

const btnLoading = ref(false)

const createOk = async (formEl:typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid:any, fields: any) => {
    if (valid) {
      if(btnLoading.value){
        return
      }
      btnLoading.value = true
      let operationApi: any = null;
      if (operation.value == "create") {
        operationApi = create(createForm.value);
      } else {
        operationApi = update(
          Object.assign(
            {
              id: operationId.value,
            },
            createForm.value
          )
        );
      }
      operationApi
        .then((res:Result) => {
          $message.success(res.message);
          close(formEl);
          emit("success");
          btnLoading.value = false
        })
        .catch((err:ResultError) => {
          $utils.errorMsg(err);
          btnLoading.value = false
        });
    }
  });
};

const menusCascader = ref([]);
const initCascader = () => {
  let obj: any = {};
  if (operationId.value) {
    obj["pid"] = operationId.value;
  }
  getCascader(obj)
    .then((res:Result) => {
      menusCascader.value = res.data.menuList;
    })
    .catch((err:ResultError) => {
      $utils.errorMsg(err);
    });
};

const pidChange = (value: any) => {
  // console.log(value);
};

const selectRuleRef = ref<any>();

const selectModalIconRef = ref<any>();

const ruleChange = (ruleItem: any) => {
  // createForm.value.menu_name = ruleItem.title;
  createForm.value.api_rule = ruleItem.rule;
};
const iconChange = (icon: string) => {
  createForm.value.icon = icon;
};

const open = (id = 0) => {
  if (id != 0) {
    operation.value = "update";
    operationId.value = id;
  } else {
    operation.value = "create";
  }
  nextTick(() => {
    toInit();
  });
  createVisible.value = true;
};

const close = async (formEl:typeof FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  operationId.value = 0;
  createVisible.value = false;
};

defineExpose({ open });
</script>
  <style scoped>
</style>